<template>
    <div class="wh-100% flex">
        <div
            class="w-70% h-full flex flex-col gap-2.5 justify-between min-w-950px"
        >
            <div class="h-60% flex gap-20px">
                <div
                    class="w-40 flex flex-col gap-10px"
                    :style="editing ? 'pointer-events: none;' : ''"
                >
                    <n-button :focusable="false" @click="showModal = true">
                        新建条目
                    </n-button>
                    <EntryItem
                        :entry="briefIntro!"
                        :current="currentEntry?.title === briefIntro?.title"
                        @click-item="(entry) => (currentEntry = entry)"
                    />
                    <div
                        style="border-bottom: solid 1px #e5e5e5"
                        class="box-border mx-2"
                    ></div>
                    <div v-if="entries.length === 0" class="flex-1">
                        <div class="flex-center h-full">暂无条目</div>
                    </div>
                    <div v-else class="flex-1 overflow-scroll">
                        <template
                            v-for="(entry, index) in entries"
                            :key="index"
                        >
                            <EntryItem
                                :entry="entry"
                                :current="entry.title === currentEntry?.title"
                                @click-item="(entry) => (currentEntry = entry)"
                            />
                        </template>
                    </div>
                </div>
                <n-card content-class="overflow-scroll flex">
                    <template #header>
                        <div
                            class="flex justify-between pb-2.5 mb-2.5"
                            style="border-bottom: solid 1px #e5e5e5"
                        >
                            <span>条目内容</span>
                            <div class="flex gap-3">
                                <n-button
                                    v-if="!editing"
                                    secondary
                                    :focusable="false"
                                    :disabled="!currentEntry"
                                    @click="handleEditContent"
                                >
                                    <template #icon>
                                        <Create />
                                    </template>
                                    编辑
                                </n-button>
                                <div v-else class="flex gap-2.5">
                                    <n-button
                                        secondary
                                        :focusable="false"
                                        @click="
                                            {
                                                editing = false;
                                                editorRef?.disableEditor();
                                            }
                                        "
                                    >
                                        <template #icon>
                                            <ArrowUndoCircle />
                                        </template>
                                        取消
                                    </n-button>
                                    <n-button
                                        :focusable="false"
                                        @click="handleSaveContent"
                                        secondary
                                        type="info"
                                    >
                                        <template #icon>
                                            <CheckmarkCircle />
                                        </template>
                                        保存
                                    </n-button>
                                </div>
                                <n-button
                                    secondary
                                    type="error"
                                    :focusable="false"
                                    :disabled="currentEntry?.title === '简介'"
                                    @click="handleDeleteEntry"
                                >
                                    <template #icon>
                                        <Trash />
                                    </template>
                                    删除
                                </n-button>
                            </div>
                        </div>
                    </template>
                    <div
                        v-if="currentEntry?.content.length === 0"
                        class="flex-1 flex-center"
                    >
                        <n-empty description="暂无内容"> </n-empty>
                    </div>
                    <div v-else v-html="currentEntry?.content"></div>
                </n-card>
            </div>
            <div class="flex-1">
                <WangEditor ref="editorRef" />
            </div>
        </div>
        <div class="w-30% box-border p-20px flex-center min-w-375px">
            <div
                class="bg-#ffffff flex flex-col w-94 h-200 pb-6 shadow rounded-xl box-border overflow-hidden"
            >
                <div
                    class="bg-#43CF7C w-full h-240px box-border p-4 flex flex-col justify-end"
                >
                    <div
                        class="w-full font-size-18px h-25 color-#fff html-content"
                        v-html="briefIntro?.content"
                    ></div>
                </div>
                <div class="flex-1 box-border p-4 overflow-scroll">
                    <n-collapse accordion>
                        <template v-for="(item, index) in entries" :key="index">
                            <n-collapse-item>
                                <template #header-extra>
                                    {{ item.title }}
                                </template>
                                <div v-html="item.content"></div>
                            </n-collapse-item>
                        </template>
                    </n-collapse>
                </div>
            </div>
        </div>
        <n-modal v-model:show="showModal">
            <n-card
                style="width: 400px"
                title="新建条目"
                :bordered="false"
                role="dialog"
                aria-modal="true"
            >
                <n-form label-placement="left">
                    <n-form-item label="条目标题">
                        <n-input v-model:value="createEntryDto.title"></n-input>
                    </n-form-item>
                </n-form>
                <template #footer>
                    <div class="w-full flex justify-end gap-2.5">
                        <n-button
                            :foucsable="false"
                            @click="
                                showModal = false;
                                Object.assign(
                                    createEntryDto,
                                    structuredClone(emptyDto)
                                );
                            "
                        >
                            取消
                        </n-button>
                        <n-button
                            type="primary"
                            :foucsable="false"
                            @click="handleCreateEntry"
                        >
                            提交
                        </n-button>
                    </div>
                </template>
            </n-card>
        </n-modal>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { Entry } from "@/types/intro.ts";
import { CreateEntryDto } from "@/service/api/dto/entry";

import {
    Create,
    Trash,
    CheckmarkCircle,
    ArrowUndoCircle,
} from "@vicons/ionicons5";

import EntryItem from "../components/entry-item/index.vue";
import WangEditor from "../components/wang-editor/index.vue";

import { throttle } from "radash";
import { getStore } from "@/store";
import {
    getEntries,
    createEntry,
    updateEntry,
    deleteEntry,
} from "@/service/api/entry";

const entryStore = getStore("entry");

const showModal = ref(false);
const editorRef = ref<InstanceType<typeof WangEditor> | null>(null);

const editing = ref(false);

const entries = ref<Entry[]>([]);
const briefIntro = ref<Entry>();
const currentEntry = ref<Entry>();

const emptyDto: CreateEntryDto = {
    title: "",
    content: "",
};
const createEntryDto = reactive<CreateEntryDto>(structuredClone(emptyDto));

const handleQueryEntry = async () => {
    try {
        await getEntries();
    } catch (err) {
        window.NMessage.error((err as Error).message);
    }
};

const handleReload = () => {
    editing.value = false;
    showModal.value = false;
    Object.assign(createEntryDto, structuredClone(emptyDto));

    briefIntro.value = entryStore.getEntryByTitle("简介");
    entries.value = entryStore.getOrdinaryEntries;

    currentEntry.value = briefIntro.value;
};

onMounted(async () => {
    if (!entryStore.getEntryLoaded) {
        await handleQueryEntry();
    }
    handleReload();
});

const handleCreateEntry = async () => {
    if (createEntryDto.title.length === 0) {
        window.NMessage.warning("请输入条目标题");
        return;
    }
    try {
        await createEntry(createEntryDto);
        window.NMessage.success("创建成功");
        await handleQueryEntry();
        handleReload();
    } catch (err) {
        window.NMessage.warning((err as Error).message);
    }
};

const handleEditContent = () => {
    editing.value = true;
    editorRef.value?.enableEditor(currentEntry.value!.content);
};

const handleSaveContent = throttle({ interval: 1000 }, async () => {
    try {
        if (!editorRef.value) {
            throw new Error("编辑器未初始化");
        }
        const content = await editorRef.value.handleSave(
            currentEntry.value!.content
        );
        if (content) {
            await updateEntry(currentEntry.value!.title, content);

            await handleQueryEntry();
            handleReload();

            editorRef.value.disableEditor();
            window.NMessage.success("修改成功");
        }
    } catch (err) {
        window.NMessage.warning((err as Error).message);
    }
});

const handleDeleteEntry = () => {
    window.NDialog.warning({
        title: "删除条目",
        content: "是否删除此条目？",
        closable: false,
        positiveText: "确认",
        negativeText: "取消",
        onPositiveClick: async () => {
            await deleteEntry(currentEntry.value!.id);

            await handleQueryEntry();
            handleReload();

            window.NMessage.success("删除成功");
        },
    });
};
</script>

<style>
.html-content {
    overflow: hidden;
    text-overflow: ellipsis;
    word-wrap: break-word; /* 允许单词内换行 */
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
}
</style>
